<template>
	<div class="merchant-shop-manage">
		<!-- 顶部导航：仅保留居中标题和右侧个人中心 -->
		<header class="page-header">
			<!-- 移除返回按钮，保留居中标题 -->
			<div class="title-container">
				<p class="header-title">店铺管理</p>
			</div>

			<!-- 个人中心按钮：保持不变 -->
			<button class="user-center-btn" @click="$router.push('/userCenter')">
				<i class="fa fa-user"></i> 个人中心
			</button>
		</header>
		<!-- 选项卡导航：原有代码不变 -->
		<div class="tabs-container">
			<button class="tab-button" :class="{ active: activeTab === 'my-shops' }" @click="activeTab = 'my-shops'">
				我的店铺
			</button>
			<button class="tab-button" :class="{ active: activeTab === 'shop-applications' }"
				@click="activeTab = 'shop-applications'">
				店铺申请
			</button>
		</div>
		<!-- 我的店铺部分：原有代码不变 -->
		<div v-if="activeTab === 'my-shops'">
			<!-- 店铺列表 -->
			<div class="shop-list-container">
				<!-- 加载状态 -->
				<div v-if="loading" class="loading">
					<i class="fa fa-spinner fa-spin"></i> 加载中...
				</div>

				<!-- 错误提示 -->
				<div v-if="error" class="error-message">
					<i class="fa fa-exclamation-circle"></i> {{ error }}
					<button @click="loadMyShops">重新加载</button>
				</div>

				<!-- 列表为空提示 -->
				<div class="empty-tip" v-if="!loading && myShops.length === 0 && !error">
					<img src="https://img.icons8.com/fluency/96/000000/empty-box.png" alt="暂无店铺" class="empty-icon">
					<p>暂无已开通的店铺，点击"申请新店铺"创建</p>
				</div>
				<!-- 店铺列表 -->
				<ul class="shop-list" v-if="!loading && myShops.length > 0">
					<li class="shop-item" v-for="(shop, index) in myShops" :key="index">
						<!-- 店铺基础信息 -->
						<div class="shop-info">
							<!-- 店铺封面图 -->
							<div class="shop-cover">
								<img :src="shop.businessImg || 'https://via.placeholder.com/150?text=店铺图片'" alt="店铺封面">
							</div>
							<!-- 核心信息 -->
							<div class="shop-main">
								<div class="shop-name-id">
									<h3 class="shop-name">{{ shop.businessName }}</h3>
									<span class="shop-id">ID: {{ shop.id }}</span>
								</div>
								<p class="shop-address"><i class="fa fa-map-marker"></i> {{ shop.businessAddress }}</p>
								<div class="shop-price">
									<span class="price-item">起送: ¥{{ shop.startPrice }}</span>
									<span class="price-item">配送: ¥{{ shop.deliveryPrice }}</span>
								</div>
								<p class="shop-time">创建时间: {{ formatDateTime(shop.createTime) }}</p>
							</div>
						</div>
						<!-- 操作按钮 -->
						<div class="shop-actions">
							<button class="btn view-btn" @click="handleViewDetail(shop)">查看详情</button>
							<button class="btn edit-btn" @click="handleEditShop(shop)">修改</button>
						</div>
					</li>
				</ul>
			</div>

			<!-- 申请新店铺按钮 -->
			<div class="add-shop-btn-container">
				<button class="add-shop-btn" @click="activeTab = 'shop-applications'">
					<i class="fa fa-plus"></i> 申请新店铺
				</button>
			</div>
		</div>
		<!-- 店铺申请部分：原有代码不变 -->
		<div v-if="activeTab === 'shop-applications'">
			<div class="shop-applications-container">
				<h3 class="section-title">店铺申请</h3>

				<!-- 加载状态 -->
				<div v-if="loadingApplications" class="loading">
					<i class="fa fa-spinner fa-spin"></i> 加载中...
				</div>

				<!-- 错误提示 -->
				<div v-if="applicationsError" class="error-message">
					<i class="fa fa-exclamation-circle"></i> {{ applicationsError }}
					<button @click="loadShopApplications">重新加载</button>
				</div>

				<!-- 申请表单 -->
				<div class="application-form">
					<h4>新增店铺申请</h4>
					<form @submit.prevent="submitShopApplication">
						<div class="form-group">
							<label>店铺名称 *</label>
							<input type="text" v-model="newShop.businessName" required>
						</div>
						<div class="form-group">
							<label>店铺地址 *</label>
							<input type="text" v-model="newShop.businessAddress" required>
						</div>
						<div class="form-group">
							<label>店铺简介</label>
							<textarea v-model="newShop.businessExplain" rows="3"></textarea>
						</div>
						<div class="form-group">
							<label>店铺图片URL</label>
							<input type="text" v-model="newShop.businessImg">
						</div>
						<div class="form-row">
							<div class="form-group">
								<label>起送价格 *</label>
								<input type="number" v-model="newShop.startPrice" min="0" required>
							</div>
							<div class="form-group">
								<label>配送费用 *</label>
								<input type="number" v-model="newShop.deliveryPrice" min="0" required>
							</div>
						</div>
						<div class="form-group">
							<label>备注</label>
							<textarea v-model="newShop.remarks" rows="2"></textarea>
						</div>
						<div class="form-actions">
							<button type="button" class="btn cancel-btn" @click="resetForm">取消</button>
							<button type="submit" class="btn submit-btn">提交申请</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	export default {
		name: 'MerchantShopManage',
		data() {
			return {
				// 选项卡状态
				activeTab: 'my-shops',

				// 我的店铺相关
				myShops: [],
				loading: false,
				error: null,

				// 店铺申请相关
				shopApplications: [],
				loadingApplications: false,
				applicationsError: null,
				newShop: {
					businessName: '',
					businessAddress: '',
					businessExplain: '',
					businessImg: '',
					startPrice: 0,
					deliveryPrice: 0,
					remarks: ''
				}
			}
		},
		created() {
			this.loadMyShops();
			this.loadShopApplications();
		},
		methods: {
			// 加载我的店铺
			async loadMyShops() {
				this.loading = true;
				this.error = null;

				try {
					const token = localStorage.getItem('jwt_token');
					if (!token) {
						throw new Error('未找到认证信息，请重新登录');
					}

					const headers = {
						'Authorization': `Bearer ${token}`
					};

					// 从localStorage获取当前用户信息（替换sessionStorage）
					const currentUser = this.$getLocalStorage('user');
					if (!currentUser || !currentUser.id) {
						throw new Error('无法获取用户信息，请重新登录');
					}

					// 方案1A：查询所有店铺，然后过滤出当前商家的店铺
					const response = await this.$axios.get('/api/businesses', {
						headers
					});
					const allBusinesses = response.data.data || [];

					// 过滤出当前商家的店铺
					this.myShops = allBusinesses.filter(business =>
						business.businessOwner && business.businessOwner.id === currentUser.id
					);

				} catch (error) {
					console.error('加载店铺列表失败:', error);
					this.error = error.response?.data?.message || error.message || '加载店铺列表失败';
				} finally {
					this.loading = false;
				}
			},

			// 加载店铺申请记录
			loadShopApplications() {
				this.loadingApplications = true;
				this.applicationsError = null;

				try {
					// 从localStorage获取当前商家的店铺申请
					const allApplications = JSON.parse(
						localStorage.getItem('allApplications') || '[]'
					);

					// 从localStorage获取当前用户ID（替换原currentUser存储键）
					const currentUser = this.$getLocalStorage('user') || {};
					const userId = currentUser.id;

					// 筛选出当前商家的店铺申请
					this.shopApplications = allApplications.filter(app =>
						app.type === 'business' && app.userId === userId
					);
				} catch (error) {
					console.error('加载店铺申请失败:', error);
					this.applicationsError = '加载店铺申请失败';
				} finally {
					this.loadingApplications = false;
				}
			},

			// 格式化日期时间
			formatDateTime(dateString) {
				if (!dateString) return '';
				const date = new Date(dateString);
				return date.toLocaleString();
			},

			// 查看店铺详情 - 跳转到详情页
			handleViewDetail(shop) {
				// 将店铺数据存储到localStorage，供详情页使用（替换sessionStorage）
				localStorage.setItem('currentShopDetail', JSON.stringify(shop));

				// 跳转到店铺详情页
				this.$router.push('/businessShopDetail');
			},

			// 编辑店铺
			handleEditShop(shop) {
				alert(`准备编辑店铺: ${shop.businessName}`);
				console.log('当前编辑的店铺信息:', shop);
			},

			// 提交店铺申请
			submitShopApplication() {
				// 表单验证
				if (!this.newShop.businessName) {
					alert('店铺名称不能为空');
					return;
				}
				if (!this.newShop.businessAddress) {
					alert('店铺地址不能为空');
					return;
				}
				if (this.newShop.startPrice < 0) {
					alert('起送价格不能为负数');
					return;
				}
				if (this.newShop.deliveryPrice < 0) {
					alert('配送费用不能为负数');
					return;
				}

				try {
					// 从localStorage获取用户信息（替换sessionStorage）
					const storedUser = this.$getLocalStorage('user');
					if (!storedUser || !storedUser.id) {
						alert('请先登录');
						return;
					}

					// 创建店铺申请对象
					const application = {
						id: Date.now(),
						type: 'business',
						userId: storedUser.id,
						userData: {
							id: storedUser.id,
							username: storedUser.username,
							firstName: storedUser.firstName,
							lastName: storedUser.lastName,
							email: storedUser.email,
							phone: storedUser.phone
						},
						businessData: {
							businessName: this.newShop.businessName,
							businessAddress: this.newShop.businessAddress,
							businessExplain: this.newShop.businessExplain,
							businessImg: this.newShop.businessImg,
							startPrice: parseFloat(this.newShop.startPrice),
							deliveryPrice: parseFloat(this.newShop.deliveryPrice),
							remarks: this.newShop.remarks,
							orderTypeId: 0
						},
						status: 'pending',
						createdAt: new Date().toISOString(),
						applicant: storedUser.username
					};

					// 保存到localStorage
					const allApplications = JSON.parse(
						localStorage.getItem('allApplications') || '[]'
					);
					allApplications.push(application);
					localStorage.setItem('allApplications', JSON.stringify(allApplications));

					alert('店铺申请提交成功，等待管理员审核');
					this.resetForm();
					this.loadShopApplications();
				} catch (error) {
					console.error('提交申请失败:', error);
					alert('提交申请失败，请重试');
				}
			},

			// 重置表单
			resetForm() {
				this.newShop = {
					businessName: '',
					businessAddress: '',
					businessExplain: '',
					businessImg: '',
					startPrice: 0,
					deliveryPrice: 0,
					remarks: ''
				};
			}
		}
	}
</script>
<style scoped>
	/* 全局样式重置 */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
		list-style: none;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}

	/* 页面容器 */
	.merchant-shop-manage {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-top: 12vw;
		padding-bottom: 15vw;
	}

	/* 顶部导航：仅标题+个人中心，标题完全居中 */
	.page-header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;
		display: flex;
		align-items: center;
		padding: 0 3vw;
		/* 左右内边距，避免个人中心贴边 */
	}

	/* 标题容器：用于确保标题居中 */
	.title-container {
		position: absolute;
		left: 0;
		right: 0;
		text-align: center;
		pointer-events: none;
		/* 允许点击穿透到下方元素 */
	}

	/* 标题样式：完全居中 */
	.header-title {
		font-size: 4.8vw;
		text-align: center;
		margin: 0;
		/* 清除默认margin */
		display: inline-block;
	}

	/* 个人中心按钮样式（居右）：保持不变 */
	.user-center-btn {
		background: none;
		border: none;
		color: #fff;
		font-size: 3.2vw;
		cursor: pointer;
		display: flex;
		align-items: center;
		gap: 1vw;
		/* 图标与文字间距 */
		width: auto;
		/* 自适应宽度，避免文字截断 */
		margin-left: auto;
		/* 强制按钮居右，增强兼容性 */
		position: relative;
		z-index: 1;
		/* 确保按钮在标题上方可点击 */
	}

	.user-center-btn i {
		font-size: 3.5vw;
		/* 图标稍大，提升辨识度 */
	}

	/* 选项卡容器：原有代码不变 */
	.tabs-container {
		display: flex;
		background-color: #fff;
		border-bottom: 1px solid #eee;
		padding: 0 3vw;
	}

	.tab-button {
		flex: 1;
		padding: 4vw 0;
		font-size: 3.5vw;
		background: none;
		border: none;
		border-bottom: 3px solid transparent;
		cursor: pointer;
		color: #666;
	}

	.tab-button.active {
		color: #0097FF;
		border-bottom: 3px solid #0097FF;
		font-weight: bold;
	}

	/* 店铺列表容器：原有代码不变 */
	.shop-list-container {
		width: 100%;
		padding: 3vw;
	}

	/* 店铺申请容器：原有代码不变 */
	.shop-applications-container {
		width: 100%;
		padding: 3vw;
	}

	.section-title {
		font-size: 4vw;
		color: #333;
		margin-bottom: 3vw;
		padding-bottom: 2vw;
		border-bottom: 1px solid #eee;
	}

	/* 加载状态：原有代码不变 */
	.loading {
		text-align: center;
		padding: 10vw;
		font-size: 4vw;
		color: #0097FF;
	}

	/* 错误提示：原有代码不变 */
	.error-message {
		background-color: #fff2f0;
		border: 1px solid #ffccc7;
		border-radius: 6px;
		padding: 4vw;
		margin: 4vw 0;
		color: #f5222d;
		text-align: center;
		font-size: 3.5vw;
	}

	.error-message button {
		margin-top: 3vw;
		padding: 2vw 4vw;
		background: #ff4d4f;
		color: white;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	/* 空列表提示：原有代码不变 */
	.empty-tip {
		width: 100%;
		padding: 15vw 0;
		text-align: center;
		color: #999;
	}

	.empty-icon {
		width: 20vw;
		height: 20vw;
		margin-bottom: 3vw;
		opacity: 0.6;
	}

	.empty-tip p {
		font-size: 3.2vw;
	}

	/* 店铺列表：原有代码不变 */
	.shop-list {
		display: flex;
		flex-direction: column;
		gap: 3vw;
	}

	/* 店铺列表项：原有代码不变 */
	.shop-item {
		width: 100%;
		background-color: #fff;
		border-radius: 8px;
		padding: 3vw;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	/* 店铺基础信息：原有代码不变 */
	.shop-info {
		display: flex;
		align-items: center;
		gap: 3vw;
		flex: 1;
	}

	/* 店铺封面图：原有代码不变 */
	.shop-cover {
		width: 25vw;
		height: 15vw;
		border-radius: 4px;
		overflow: hidden;
	}

	.shop-cover img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 店铺核心信息：原有代码不变 */
	.shop-main {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 1.5vw;
	}

	/* 店铺名+ID：原有代码不变 */
	.shop-name-id {
		display: flex;
		align-items: center;
		gap: 2vw;
	}

	.shop-name {
		font-size: 3.5vw;
		color: #333;
		font-weight: 600;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.shop-id {
		font-size: 2.8vw;
		color: #999;
	}

	/* 店铺地址：原有代码不变 */
	.shop-address {
		font-size: 3vw;
		color: #666;
		display: flex;
		align-items: center;
		gap: 1.5vw;
	}

	/* 店铺价格：原有代码不变 */
	.shop-price {
		display: flex;
		gap: 3vw;
		font-size: 2.8vw;
		color: #666;
	}

	.price-item {
		background-color: #f5f5f5;
		padding: 0.5vw 2vw;
		border-radius: 2vw;
	}

	/* 店铺时间：原有代码不变 */
	.shop-time {
		font-size: 2.8vw;
		color: #999;
	}

	/* 操作按钮：原有代码不变 */
	.shop-actions {
		display: flex;
		gap: 2vw;
	}

	/* 按钮样式：原有代码不变 */
	.btn {
		padding: 1.5vw 3vw;
		border-radius: 4px;
		font-size: 3vw;
		font-weight: 500;
		border: none;
		cursor: pointer;
	}

	.view-btn {
		background-color: #e6f4ff;
		color: #0097FF;
	}

	.edit-btn {
		background-color: #e6f7ef;
		color: #38CA73;
	}

	.delete-btn {
		background-color: #fff2f0;
		color: #ff4d4f;
	}

	/* 申请新店铺按钮容器：原有代码不变 */
	.add-shop-btn-container {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw 3vw 0 3vw;
	}

	/* 申请新店铺按钮：原有代码不变 */
	.add-shop-btn {
		width: 100%;
		height: 10vw;
		font-size: 3.8vw;
		font-weight: 700;
		color: #fff;
		background-color: #38CA73;
		border-radius: 4px;
		border: none;
		outline: none;
	}

	/* 申请表单：原有代码不变 */
	.application-form {
		background-color: #fff;
		border-radius: 8px;
		padding: 3vw;
		margin-bottom: 3vw;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	.application-form h4 {
		font-size: 3.5vw;
		color: #333;
		margin-bottom: 3vw;
		padding-bottom: 2vw;
		border-bottom: 1px solid #eee;
	}

	/* 表单样式：原有代码不变 */
	form {
		display: flex;
		flex-direction: column;
		gap: 3vw;
	}

	.form-group {
		display: flex;
		flex-direction: column;
		gap: 1.5vw;
	}

	.form-row {
		display: flex;
		gap: 2vw;
	}

	.form-row .form-group {
		flex: 1;
	}

	.form-group label {
		font-size: 3.2vw;
		color: #333;
		font-weight: 500;
	}

	.form-group input,
	.form-group textarea {
		padding: 2vw;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 3.2vw;
		background-color: #f9f9f9;
	}

	.form-group input:focus,
	.form-group textarea:focus {
		outline: none;
		border-color: #0097FF;
	}

	.form-actions {
		display: flex;
		gap: 2vw;
		margin-top: 3vw;
	}

	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
	}

	.submit-btn {
		background-color: #0097FF;
		color: #fff;
	}

	/* 弹窗遮罩：原有代码不变 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 2000;
	}

	/* 弹窗内容：原有代码不变 */
	.modal-content {
		width: 85%;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	/* 弹窗头部：原有代码不变 */
	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 3vw 3vw;
		border-bottom: 1px solid #f5f5f5;
	}

	.modal-header h4 {
		font-size: 3.5vw;
		color: #333;
		font-weight: 600;
	}

	.close-icon {
		font-size: 4vw;
		color: #999;
		cursor: pointer;
	}

	/* 弹窗主体：原有代码不变 */
	.modal-body {
		padding: 3vw;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 3vw;
	}

	/* 详情页头像：原有代码不变 */
	.detail-avatar {
		width: 25vw;
		height: 25vw;
		border-radius: 4px;
		overflow: hidden;
	}

	.detail-avatar img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 详情信息列表：原有代码不变 */
	.detail-info {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 2.5vw;
	}

	/* 详情项：原有代码不变 */
	.detail-item {
		display: flex;
		font-size: 3.2vw;
	}

	.detail-label {
		width: 28%;
		color: #666;
		font-weight: 500;
	}

	.detail-value {
		width: 72%;
		color: #333;
	}

	/* 弹窗底部：原有代码不变 */
	.modal-footer {
		padding: 3vw;
		border-top: 1px solid #f5f5f5;
	}

	.confirm-btn {
		width: 100%;
		height: 11vw;
		background-color: #0097FF;
		color: #fff;
		border: none;
		border-radius: 4vw;
		font-size: 3.2vw;
		font-weight: 500;
		cursor: pointer;
	}
</style>